import json
import time
from Cipher_AES import decrypt,encrypt
import Utils

# 3D447D15: systemSupport-min.js
# 8D59698F: application-min.js
# CA13C948: index-min.js
# C2E8189D: bundle-min.js
# D5CA85CF: babelHelpers-min.js

import requests
import os

rootDir = os.getcwd()

def correction_version():
    f = requests.get("https://remote-data.oss-cn-shanghai.aliyuncs.com/data/cc3buildTool-version.json",timeout=2)
    version_info = json.loads(f.text)
    version_info['lastTime'] = time.strftime('%H') #记录登陆时间
    text = encrypt(json.dumps(version_info))
    Utils.writeInFile(f'{rootDir}/bin/F14FC43A.wasm',text)
    for k,_ in version_info.items():
       if k == 'lastTime':
           continue
       if os.path.exists(f'{rootDir}/bin/{k}.wasm'):
           os.remove(f'{rootDir}/bin/{k}.wasm')
       f = requests.get(f'https://remote-data.oss-cn-shanghai.aliyuncs.com/files/{k}.wasm',timeout=2)
       Utils.writeBinInFile(f'{rootDir}/bin/{k}.wasm',f.content)


def pull( func:None = None ):

    flag = False
    if not os.path.exists(f'{rootDir}/bin'):
        os.makedirs(f'{rootDir}/bin')
    if not os.path.exists(f'{rootDir}/bin/F14FC43A.wasm'):
        correction_version()
        flag = True
    else:
        text = decrypt(Utils.fromFile(f'{rootDir}/bin/F14FC43A.wasm'))
        local_version = json.loads(text)

        #每小时更新一次
        if abs(int(local_version['lastTime']) - int(time.strftime('%H'))) >= 1:
            flag = True
            try:
                f = requests.get("https://remote-data.oss-cn-shanghai.aliyuncs.com/data/cc3buildTool-version.json",timeout=2)
            except:
                print(">>>> 请关闭翻墙软件 并重新运行程序")
                return
            version_info = json.loads(f.text)
            version_info['lastTime'] = time.strftime('%H') #记录登陆时间
            text = encrypt(json.dumps(version_info))
            Utils.writeInFile(f'{rootDir}/bin/F14FC43A.wasm',text)
            for k,_ in version_info.items():
                #版本变动更新
                if k == 'lastTime' or float(_['ver']) == float(local_version[k]['ver']):
                    continue
                if os.path.exists(f'{rootDir}/bin/{k}.wasm'):
                    os.remove(f'{rootDir}/bin/{k}.wasm')
                f = requests.get(f'https://remote-data.oss-cn-shanghai.aliyuncs.com/files/{k}.wasm',timeout=2)
                Utils.writeBinInFile(f'{rootDir}/bin/{k}.wasm',f.content)
                print(f"> upgrade file: {k}.wasm .... ....")

    if func != None:
        func(flag)

url_map = {
  "systemSupport-min.js": "3D447D15",
  "application-min.js": "8D59698F",
  "index-min.js": "CA13C948",
  "bundle-min.js": "C2E8189D",
  "babelHelpers-min.js": "D5CA85CF"
}

def getScript(key:str):
    if not key in url_map.keys():
        return
    url = f'{rootDir}/bin/{url_map[key]}.wasm'
    if not os.path.exists(url):
        correction_version()
    return decrypt(Utils.fromFile(url))
